package com.ibis.debuglistwidget;

import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;

public class PrefsActivity extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {
    // private int appWidgetId;
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private ListPreference mRefreshFrequencyPreference;
    private ListPreference mLevelPreference;
    private ListPreference mFormatPreference;
    private ListPreference mBufferPreference;
    private ListPreference mTextsizePreference;
    // private ListPreference mBackgroundColorPreference;
    private ListPreference mPeriodicFrequencyPreference;
    private Prefs mPrefs;

    // private SaveScheduler mSaveScheduler;

    public PrefsActivity() {
        super();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
        // Set the result to CANCELED. This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED, null);
        // Build GUI from resource
        addPreferencesFromResource(R.layout.prefs);

        mPrefs = new Prefs(this);
        // mSaveScheduler = new SaveScheduler(this);

        // Bind the action for the save button.
        // findViewById(R.id.save_button).setOnClickListener(mOnClickListener);

        // Find the widget id from the intent.
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }

//        temporary
        // If they gave us an intent without the widget id, just bail.
//        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
//            finish();
//        }

        mRefreshFrequencyPreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.REFRESH_FREQUENCY_KEY);
        mLevelPreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.LEVEL_KEY);
        mFormatPreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.FORMAT_KEY);
        mBufferPreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.BUFFER_KEY);
        mTextsizePreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.TEXTSIZE_KEY);
        // mBackgroundColorPreference = (ListPreference) getPreferenceScreen()
        // .findPreference(Prefs.BACKGROUND_COLOR_KEY);
        mPeriodicFrequencyPreference = (ListPreference) getPreferenceScreen()
                .findPreference(Prefs.PERIODIC_FREQUENCY_KEY);

        prepareSaveBtn();
//        setResult(RESULT_OK, resultValue);
//        setResult(RESULT_OK);
//        finish();
    }

    private void prepareSaveBtn() {
        // final Context context = this;
        Preference pref = findPreference("SAVE");
        // Bind the "onClick" for the save preferences to close the activity
        // and postback "OK"
        if (pref != null) {
            pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                public boolean onPreferenceClick(final Preference preference) {

                    int[] appWidgetIds = {mAppWidgetId};
                    Intent intent = new Intent(
                            AppWidgetManager.ACTION_APPWIDGET_UPDATE);
                    intent.putExtra(
                            AppWidgetManager.EXTRA_APPWIDGET_IDS,
                            appWidgetIds);
                    sendBroadcast(intent);

                    // Make sure we pass back the original appWidgetId
                    Intent resultValue = new Intent();
                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                            mAppWidgetId);
                    setResult(RESULT_OK, resultValue);

                    // Intent resultValue = new Intent();
                    // resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    // mAppWidgetId);
                    // setResult(RESULT_OK, resultValue);
                    // // StocksProvider.loadFromYahooInBackgroud(context,
                    // // appWidgetId);
                    // // UpdateService.registerService(context);
                    finish();
                    return true;
                }
            });
        }
    }



    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        int widgetId = extras != null ? extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID) : 0;

        // this is the intent broadcast/returned to the widget Intent
        Intent updateIntent = new Intent(this, LogWidgetProvider.class);
        updateIntent.setAction(LogWidgetProvider.REFRESH_ACTION);
        updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
        sendBroadcast(updateIntent);
    }

    // View.OnClickListener mOnClickListener = new View.OnClickListener() {
    // public void onClick(View v) {
    // // final Context context = PrefsActivity.this;
    //
    // // When the button is clicked, save the string in our prefs and
    // // return that they
    // // clicked OK.
    // // String titlePrefix = mAppWidgetPrefix.getText().toString();
    // // saveTitlePref(context, mAppWidgetId, titlePrefix);
    //
    // // Push widget update to surface with newly set prefix
    // // AppWidgetManager appWidgetManager = AppWidgetManager
    // // .getInstance(context);
    // // LogWidgetProvider.updateAppWidget(context, appWidgetManager,
    // // mAppWidgetId, new String("a"));
    //
    // // Make sure we pass back the original appWidgetId
    // // Intent resultValue = new Intent();
    // // resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
    // // mAppWidgetId);
    // // setResult(RESULT_OK, resultValue);
    // // finish();
    // // Push widget update to surface with newly set prefix
    //
    // int[] appWidgetIds = { mAppWidgetId };
    // Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    // intent.putExtra(
    // android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_IDS,
    // appWidgetIds);
    // sendBroadcast(intent);
    //
    // // Make sure we pass back the original appWidgetId
    // Intent resultValue = new Intent();
    // resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
    // mAppWidgetId);
    // setResult(RESULT_OK, resultValue);
    // finish();
    // }
    // };

    private void setRefreshFrequencyTitle() {
        mRefreshFrequencyPreference.setTitle("Widget refresh Frequency? ("
                + mPrefs.getRefreshFrequency().getTitle(this) + ")");
    }

    private void setLevelTitle() {
        mLevelPreference.setTitle("Level? (" + mPrefs.getLevel().getTitle(this)
                + ")");
    }

    private void setFormatTitle() {
        mFormatPreference.setTitle("Format? ("
                + mPrefs.getFormat().getTitle(this) + ")");
    }

    private void setBufferTitle() {
        // mBufferPreference.setTitle("Buffer? (" +
        // mPrefs.getBuffer().getTitle(this) + ")");
    }

    private void setTextsizeTitle() {
        mTextsizePreference.setTitle("Text Size? ("
                + mPrefs.getTextsize().getTitle(this) + ")");
    }

    // private void setBackgroundColorTitle() {
    // mBackgroundColorPreference.setTitle("Background Color? ("
    // + mPrefs.getBackgroundColor().getTitle(this) + ")");
    // }

    private void setPeriodicFrequencyTitle() {
        mPeriodicFrequencyPreference.setTitle("Frequency? ("
                + mPrefs.getPeriodicFrequency().getTitle(this) + ")");
    }

    private void setPeriodicState() {
        if (mPrefs.isPeriodicSave()) {
            mPeriodicFrequencyPreference.setEnabled(true);
        } else {
            mPeriodicFrequencyPreference.setEnabled(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        setRefreshFrequencyTitle();
        setLevelTitle();
        setFormatTitle();
        setBufferTitle();
        setTextsizeTitle();
        // setBackgroundColorTitle();
        // setPeriodicFrequencyTitle();

        // setPeriodicState();

        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(Prefs.LEVEL_KEY)) {
            setLevelTitle();
        } else if (key.equals(Prefs.REFRESH_FREQUENCY_KEY)) {
            setRefreshFrequencyTitle();
        } else if (key.equals(Prefs.FORMAT_KEY)) {
            setFormatTitle();
        } else if (key.equals(Prefs.BUFFER_KEY)) {
            setBufferTitle();
        } else if (key.equals(Prefs.TEXTSIZE_KEY)) {
            setTextsizeTitle();
            // } else if (key.equals(Prefs.BACKGROUND_COLOR_KEY)) {
            // setBackgroundColorTitle();
        } else if (key.equals(Prefs.PERIODIC_FREQUENCY_KEY)) {
            setPeriodicFrequencyTitle();

            // restart with no frequency
            // mSaveScheduler.stop();
            // mSaveScheduler.start();
        } else if (key.equals(Prefs.PERIODIC_SAVE_KEY)) {
            setPeriodicState();

            if (mPrefs.isPeriodicSave()) {
                // mSaveScheduler.start();
            } else {
                // mSaveScheduler.stop();
            }
        }
    }
}